package com.example.horizonserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.horizonserver.common.exception.VehicleEecption;
import com.example.horizonserver.common.exception.VehicleSaveException;
import com.example.horizonserver.common.result.PageResult;
import com.example.horizonserver.mapper.VehicleMapper;
import com.example.horizonserver.pojo.DTO.VehicleDTO;
import com.example.horizonserver.pojo.DTO.VehiclePageQueryDTO;
import com.example.horizonserver.pojo.entity.Vehicle;
import com.example.horizonserver.service.VehicleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class VehicleServiceImpl implements VehicleService {

    @Autowired
    private VehicleMapper vehicleMapper;
    /**
     * 保存车辆信息
     * @param vehicleDTO
     */
    @Override
    @CacheEvict(cacheNames = "vehiclePageCache", allEntries = true)
    public void save(VehicleDTO vehicleDTO) {
        //验证车牌号唯一性
        String number = vehicleDTO.getNumber();
        LambdaQueryWrapper<Vehicle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Vehicle::getNumber, number);
        Vehicle vehicle = vehicleMapper.selectOne(lqw);
        if(vehicle != null)
        {
            throw new VehicleSaveException("车牌号已存在");
        }
        Vehicle newVehicle = new Vehicle();
        //实体类转化
        //对象属性拷贝 BeanUtils.copyProperties
        BeanUtils.copyProperties(vehicleDTO, newVehicle);
        newVehicle.setStatus(1);
        newVehicle.setLastUseTime(LocalDateTime.now());
        newVehicle.setLastMaintainTime(LocalDateTime.now());
        vehicleMapper.insert(newVehicle);
    }

    /**
     * 分页条件查询车辆信息
     * @param vehiclePageQueryDTO
     * @return
     */
    @Override
    @Cacheable(
            value = "vehiclePageCache",
            key = "'page:' + #vehiclePageQueryDTO.page + ':' + #vehiclePageQueryDTO.pageSize",
            condition = "#vehiclePageQueryDTO.pageSize==5"+
                    "&&(#vehiclePageQueryDTO.name == null || #vehiclePageQueryDTO.name == '') " +
                    "&& (#vehiclePageQueryDTO.categoryName == null || #vehiclePageQueryDTO.categoryName == '') " +
                    "&& #vehiclePageQueryDTO.status == null || #vehiclePageQueryDTO.status == ''"
    )
    public PageResult pageQuery(VehiclePageQueryDTO vehiclePageQueryDTO) {
        //判断前端是否传page和pageSize参数
        if(vehiclePageQueryDTO.getPage() == null|| vehiclePageQueryDTO.getPageSize() == null)
        {
            throw new VehicleEecption("未指定页数和每页数据数");
        }
        //判断status是否符合规矩
        if(vehiclePageQueryDTO.getStatus() != null && vehiclePageQueryDTO.getStatus() != 1
                && vehiclePageQueryDTO.getStatus() != 2&& vehiclePageQueryDTO.getStatus() != 3
                && vehiclePageQueryDTO.getStatus() != 4)
        {
            throw new VehicleEecption("车辆状态不合法");
        }
        // 构建分页参数
        Page<Vehicle> page = new Page<>(vehiclePageQueryDTO.getPage(), vehiclePageQueryDTO.getPageSize());
        // 构建查询条件
        LambdaQueryWrapper<Vehicle> lqw = new LambdaQueryWrapper<>();
        // 车辆型号模糊查询
        lqw.like(StringUtils.isNotBlank(vehiclePageQueryDTO.getName()),
                Vehicle::getName, vehiclePageQueryDTO.getName());
        // 车辆分类精确查询
        lqw.eq(StringUtils.isNotBlank(vehiclePageQueryDTO.getCategoryName()),
                Vehicle::getCategoryName, vehiclePageQueryDTO.getCategoryName());
        // 车辆状态精确查询
        lqw.eq(vehiclePageQueryDTO.getStatus() != null,Vehicle::getStatus,
                vehiclePageQueryDTO.getStatus());
        // 执行分页查询
        IPage<Vehicle> vehiclePage = vehicleMapper.selectPage(page, lqw);
        // 封装返回结果
        PageResult pageResult = new PageResult();
        pageResult.setTotal(vehiclePage.getTotal());
        pageResult.setRecords(vehiclePage.getRecords());
        return pageResult;
    }

    /**
     * 批量删除车辆信息
     * @param ids
     */
    @Override
    @CacheEvict(cacheNames = "vehiclePageCache", allEntries = true)
    public void deleteBatch(List<Integer> ids) {
        //根据员工id集合动态批量删除员工数据
        List<Vehicle> vehicles = vehicleMapper.selectByIds(ids);
        if(vehicles.size() != ids.size())
        {
            throw new VehicleEecption("存在不存在的车辆");
        }
        //如果有状态不是可用的车辆,也不许删除
        for(Vehicle vehicle : vehicles)
        {
            if(vehicle.getStatus() != 1)
            {
                throw new VehicleEecption("车辆状态不可用,不可删除,车牌号:"+vehicle.getNumber());
            }
        }
        vehicleMapper.deleteByIds(ids);
    }

    /**
     * 根据id查询车辆信息 用作修改回显 以及申请时的信息显示
     * @param id
     * @return
     */
    @Override
    public Vehicle getById(Integer id) {
        Vehicle vehicle = vehicleMapper.selectById(id);
        if(vehicle == null)
        {
            throw new VehicleEecption("车辆不存在");
        }
        return vehicle;
    }

    /**
     * 修改车辆信息
     * @param vehicleDTO
     */
    @Override
    @CacheEvict(cacheNames = "vehiclePageCache", allEntries = true)
    public void update(VehicleDTO vehicleDTO) {
        if(vehicleMapper.selectById(vehicleDTO.getId())==null)
        {
            throw new VehicleEecption("车辆不存在");
        }
        if(vehicleMapper.selectById(vehicleDTO.getId()).getStatus()!=1)
        {
            throw new VehicleEecption("车辆状态占用中,不可修改,车牌号:"+
                    vehicleMapper.selectById(vehicleDTO.getId()).getNumber());
        }
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleDTO,vehicle);
        vehicleMapper.updateById(vehicle);
    }
}
